package dao;

import pojo.User;

import java.sql.*;

//数据访问层(数据库的交互)
public class UserDao {
    final String USER_NAME = "root";
    final String PASSWORD = "123456";
    final  String URL = "jdbc:mysql://localhost:3306/user";
    public User CheckLogin(User loginuser) throws SQLException {
        User user = null;
//        Connection conn = null;
//        ResultSet rs = null;
        //注册驱动(确认使用那个数据库)
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        //连接数据库
        Connection conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        //编写SQL语句
        String sql="select id,username,password from user where username=? and password=?";
        //把SQL语句发送给数据库(数据库执行代码,并返回执行结果)
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,loginuser.getUserName());
        pstmt.setString(2,loginuser.getUserPassword());
        ResultSet rs = pstmt.executeQuery();
        //处理SQL的执行结果
        if(rs!=null&&rs.next()){
            String username = rs.getString("username");
            Integer userId = rs.getInt("id");
            String password = rs.getString("password");

            user=new User(userId,password,username);
        }
        return user;
    }
}
